const CartHttp=require("../../models/CartHttp")

Page({
  data: {
    carts:[],
    allChecked:"",
    sum:0
  },
  
  async onLoad() {
    var res=await CartHttp.getCart();
    var allChecked=res.data.every(item=>{
      return item.isSelected;
    })
    this.setData({
      carts:res.data,
      allChecked
    })
    this.handleSum()
  },
  handleNum(event){
    /* 通过id值，找到数组中对应的项目，将项目中的productCount更改 */
    var carts=this.data.carts;
    var {aid}=event.currentTarget.dataset;
    carts.forEach(item=>{
      if(item.id==aid){
        item.productCount=event.detail
      }
    })
    this.setData({
      carts
    })
    this.handleSum()
  },
  handleSelect(event){
    /* 实现单个itemcheckbox的变换 */
    var carts=this.data.carts;
    var {aid}=event.currentTarget.dataset;
    carts.forEach(item=>{
      if(item.id==aid){
        item.isSelected=event.detail
      }
    })
    var allChecked=carts.every(item=>{
      return item.isSelected;
    })
    this.setData({
      carts,
      allChecked
    })
    this.handleSum()
  },
  handleAll(event){
    /* 处理全选 */
    var carts=this.data.carts;;
    carts.forEach(item=>{
      item.isSelected=event.detail;
    })
    this.setData({
      allChecked:event.detail,
      carts
    })
    this.handleSum()
  },
  handleSum(){
    /* 计算总价 */
    var sum=0;
    var carts=this.data.carts;
    carts.forEach(item=>{
      if(item.isSelected){
        sum+=(item.productCount)*(item.productPrice)
      }
    })
    this.setData({
      sum:sum*100
    })
  }
  
})
